//use command:[cnpm config get prefix] to see path.
/*
 * NOTE:All js need to debug with alfred.
 */
var AlfredNode = require('alfred-workflow-nodejs');
var actionHandler = AlfredNode.actionHandler;

var workflow = AlfredNode.workflow;
workflow.setName("nodejs-workflow-urls");

var utils = require('../AlfredWorkflowUtils.js');
var mysql = require('../AlfredWorkflowMysqlServer.js');

var cons = require('consolidate');

var token = process.argv[2].trim();

function renderMustache(source){
	 cons.mustache(__dirname+'/script-input.xml', source)
	 .then(function (res) {
	 console.log(res);
	 })
	 .catch(function (err) {
	 throw err;
	 });
}

var params = ['%'+token+"%"];
var sql = 'select * from alfred_workflow_urls where keyword like ? order by last_check_time desc limit 10';
var tmpl = {isEmpty:false,items:[]};
var item ={uid:"",arg:"",valid:"",title:"",subtitle:""};
tmpl.items.push(item);
tmpl.items.push(item);
// renderMustache(tmpl);
// return false;


mysql.executeSql(sql,params).then(
		function(rows) {
			if(rows&&rows.length>0){
				rows.forEach(function(item, index, array) {
					tmpl.items.push({
						title : item.url,
						subtitle : item.desc,
						arg : item.id+","+item.url,
						valid : true
					}));
				});
			}else{
				workflow.addItem(tmpl.items.pus({
					title : "empty",
					subtitle : "empty for params:"+params,
					arg : "",
					valid : true 
				}));
			}
			renderMustache(tmpl);
			return;
		}).catch(function(err){
			workflow.addItem(new AlfredNode.Item({
				title : "opps,error",
				subtitle : 'opps,error,check ~/tools/myGit/xNode/alfred/url/AlfredWorkflowUrl.js',
				arg : "",
				hasSubItems : false,
				valid : true,
				data : {
					alias : "X"
				}
			}));
			workflow.feedback();
		});

